<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间" prop="date">
        <el-date-picker
          v-model="queryParams.month"
          value-format="yyyy-MM"
          type="month"
          placeholder="请选择月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="班组" prop="classID">
        <el-select clearable v-model="queryParams.classID" placeholder="请选择班组">
          <el-option
            v-for="item in groups"
            :key="item.classId"
            :label="item.className"
            :value="item.classId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" size="mini" @click="addAttendanceVisible=true">新增</el-button>
<!--        <el-button type="primary" size="mini" @click="handleQuery">开始编辑</el-button>
        <el-button type="success" size="mini" @click="submit">保存</el-button>-->
        <!--        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="postList_info" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column prop="classId" label="班组类别" width="80" align="center">
        {{ queryParams.classID }}
      </el-table-column>
      <el-table-column prop="post" label="职位" width="80" align="center"></el-table-column>
      <el-table-column prop="userId" label="姓名" :formatter="formatteruserName" width="80" align="center"></el-table-column>
<!--      <el-table-column label="倒班情况" width="80" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:attendance:edit']"
          >选择
          </el-button>
        </template>
      </el-table-column>-->
      <el-table-column label="集控中心月排班表" align="center">
        <el-table-column v-for="(item, index) in everyDay" :key="index" :prop="dateindex[index]" :render-header="renderHeader" :label="item+'/'+(index+1+'')" width="80" align="center" >
<!--        <el-table-column v-for="(item, index) in everyDay" :key="item" :props="dateindex[index]" :label="item" width="80" align="center" >-->
            <template slot-scope="scope">
              {{attendanceStatusFormat(scope.row[dateindex[index]])}}
<!--              <span v-if="scope.row[dateindex[index]]">{{attendanceStatusFormat(scope.row[dateindex[index]])}}</span>
&lt;!&ndash;              <span v-if="scope.row[index + 1]">{{attendanceStatusFormat(scope.row[index + 1])}}</span>&ndash;&gt;
              <span v-else>休</span>-->
            </template>
            <!--template slot-scope="scope">
              <el-select v-model="arr[index + 1]" slot="prepend" placeholder="请选择">
                <el-option label="白班" value="1"></el-option>
                <el-option label="夜班" value="2"></el-option>
              </el-select>
&lt;!&ndash;              {{postList_info[scope.$index][index+1]}}&ndash;&gt;
            </template>-->
<!--            <el-input v-if=" row.date.getDate()==index+1" :disabled="true"  prop="status"/>-->
        </el-table-column>
      </el-table-column>
    </el-table>

    <!-- 新增排班的对话框 -->
    <el-dialog title="新增排班表" :visible.sync="addAttendanceVisible" width="85%">
      <el-form :model="addParams" ref="queryForm" :inline="true">
        <el-form-item label="时间" prop="date">
          <el-date-picker
            v-model="addParams.month"
            value-format="yyyy-MM"
            type="month"
            placeholder="请选择月份">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="班组" prop="classID">
          <el-select clearable v-model="addParams.classID" placeholder="请选择班组">
            <el-option
              v-for="item in groups"
              :key="item.classId"
              :label="item.className"
              :value="item.classId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  size="mini" @click="startEdit">开始编辑</el-button>
          <el-button type="primary" size="mini" @click="saveAddAttendance">保存</el-button>
        </el-form-item>

<!--        v-loading="loading"-->
        <el-table :data="addAttendance_info" style="width: 100%">
          <el-table-column prop="classId" label="班组类别" width="80" align="center">
            {{ addParams.classID }}
          </el-table-column>
          <el-table-column prop="post" label="职位" width="80" align="center"></el-table-column>
          <el-table-column prop="userId" label="姓名" :formatter="formatteruserName" width="80" align="center"></el-table-column>
          <el-table-column prop="workShiftType" label="倒班情况" width="150" align="center">
            <template slot-scope="scope">
              <el-select clearable v-model="scope.row.workShiftType" placeholder="选择倒班方式" @change="changeShiftType(scope)">
                <el-option
                  v-for="dict in workShiftTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="集控中心月排班表" align="center" >
            <el-table-column v-for="(item, index) in addEveryDay" :key="index" :prop="addDateindex[index]" :render-header="renderHeader" :label="item+'/'+(index+1+'')" width="100" align="center" >
<!--            <el-table-column v-for="(item, index) in addEveryDay" :key="item" :props="addDateindex[index]" :label="item" width="80" align="center" >-->
<!--              <el-table-column
                :label="index + 1+''"
                align="center"
                width="100">-->
                <template slot-scope="scope">
                  <span v-if="scope.row.workShiftType==1">
                    {{ scope.row[addDateindex[index]] }}
<!--                    <span v-if="item=='周六'||item=='周日'">{{ scope.row[addDateindex[index]] }}</span>
                    <span v-else>{{attendanceStatusFormat(scope.row[addDateindex[index]])}}</span>-->
                  </span>
                  <span v-if="scope.row.workShiftType==2">
                    {{ scope.row[addDateindex[index]] }}
<!--                    <span v-if="item=='周六'||item=='周日'">{{attendanceStatusFormat(scope.row[addDateindex[index]])}}</span>
                    <span v-else>休</span>-->
                  </span>
                  <span v-if="scope.row.workShiftType==3">
                    <el-select clearable v-model="scope.row[addDateindex[index]]" placeholder="请选择" @change="dayOrNight(addAttendance_info,scope.$index,scope.row)">
<!--                    <el-select v-model="arr[index + 1]" slot="prepend" placeholder="请选择">-->
                      <el-option label="白班" value="白"></el-option>
                      <el-option label="夜班" value="夜"></el-option>
                    </el-select>
                  </span>
                </template>
<!--              </el-table-column>-->
            </el-table-column>
          </el-table-column>
        </el-table>

      </el-form>


    </el-dialog>

    <!-- 添加或修改考勤对话框 -->
    <el-dialog :title="title" :visible.sync="open"  append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in attendanceStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.date"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listAttendance,
  getAttendance,
  delAttendance,
  addAttendance,
  updateAttendance,
  exportAttendance, saveAttendances,
} from "@/api/system/attendance";
import {listUser, selectByClassID} from "@/api/system/user";
import {listClass} from "@/api/system/class";
import {getDicts} from "@/api/system/dict/data";

export default {
  name: "Attendance",
  data() {
    return {
      //班组列表
      groups:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考勤表格数据
      attendanceList: [],
      // 用户回显列表
      userList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      attendanceStatusOptions: [],
      workShiftTypeOptions:[],
      postList_info:[],
      addAttendance_info:[],
      everyDay : null,
      dateindex : null,
      addEveryDay : null,
      addDateindex : null,
      // 查询参数
      queryParams: {
        classID: null,
        month: null
      },
      //新增排班的参数
      addParams:{
        classID: null,
        month: null
      },
      addAttendanceVisible:false,
      arr:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
    };
  },
  created() {
    listUser().then(response => {
      this.userList = response.rows;
      this.loading = false;
    });
    this.getAttendanceList();
    this.getClass()
    //获取字典
    this.getDicts("sys_attendance_status").then(response => {
      this.attendanceStatusOptions = response.data;
      console.log(this.attendanceStatusOptions)
    });
    this.getDicts("sys_shift_type").then(response => {
      this.workShiftTypeOptions = response.data;
      console.log(this.workShiftTypeOptions)
    });
  },
  methods: {
    /** 选择器响应式更新视图 */
    dayOrNight(data,index,row){
      this.$set(data,index,row)
    },
    /** 表头换行 */
    renderHeader(h, { column }) {
      return h('span', {}, [
        h('span', {}, column.label.split('/')[0]),
        h('br'),
        h('span', {}, column.label.split('/')[1])
      ])
    },
    /** 翻译排班状态字典 */
    attendanceStatusFormat(value){
      return this.selectDictLabel(this.attendanceStatusOptions,value)
    },
    workShiftTypeFormat(value){
      return this.selectDictLabel(this.workShiftTypeOptions,value)
    },
    /** 查询班组信息 */
    async getClass(){
      await listClass().then(res=>{
        this.groups=res.rows
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getEveryDay(this.queryParams.month,"query")
      this.getAttendanceList();
    },
    /** 新增排班时开始编辑按钮 */
    startEdit(){
      this.getEveryDay(this.addParams.month,"add")
      this.getClassInfo(this.addParams.classID)
    },
    /** 查询考勤列表 */
    async getAttendanceList() {
      let arr;
      this.loading = true;
      await getAttendance(this.queryParams).then(response => {
        console.log("查询：")
        console.log(response)
        this.attendanceList = response.rows;
        arr = this.attendanceList;
        if(response.total==0){
          return this.$message.info("未查询到此排班信息！");
        }
      });
      this.loading = false
      this.resetArr(arr)
    },
    async getClassInfo(classId){
      await selectByClassID({classID:classId}).then(res=>{
        console.log(res)
        this.addAttendance_info=res.rows
      })
    },
    getEveryDay(date,flag) {//queryParams.month
      console.log("date:")
      console.log(date)
      // const yearandMonth = this.getYearandMonth()
      const yearandMonth =date
      var date = new Date(date)
      var month = new Date(date).getMonth()
      date.setMonth(month + 1);
      date.setDate(0);
      const dayArry = [];
      // const peoplelist = {};
      const dateArray = [];
      // 获取月份的某一天
      const day = date.getDate();
      for (let i = 1; i <= day; i++) {
        date.setDate(i); // 如果只获取当前选择月份的每一天，则不需要date.setDate(i)只需dayArry.push(i)即可，其中date.setDate(i)是设置当前月份的每一天
        dayArry.push(this.getWeekday(date.getDay())); // 选中月份的每一天和当天是星期几
        const strday = ("0" + i).slice(-2); //获取当前日（1-31日）
        dateArray.push(yearandMonth + "-"+strday);
      }
      console.log("dateArr:")
      console.log(dateArray)
      if(flag=="query") {
        this.dateindex = dateArray;
        this.everyDay = dayArry;
      }
      else if(flag=="add"){
         this.addDateindex=dateArray;
         this.addEveryDay=dayArry;
      }
    },
    getWeekday(day) {
      return ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][day];
    },
    getYearandMonth() {
      const nowdata = new Date(new Date().getTime());
      const year = nowdata.getFullYear();
      const month = ("0" + (nowdata.getMonth() + 1)).slice(-2); //获取当前月份（0~11，0代表1月）
      return year +"-"+ month;
    },
    resetArr(arr) {
      let obj = {}, result = [] ,index = 0;
      arr.forEach(item=>{
        //Object的hasOwnProperty()方法返回一个布尔值，判断对象是否包含特定的自身（非继承）属性。
        //判断属性对象中是否存在这个相同key，若存在就赋值
        if(obj.hasOwnProperty(item.userId)){
          result[obj[item.userId]][item.date] = item.status || 0;
        }else{
          obj[item.userId] = index++;
          result.push({
            id: item.id,
            userId: item.userId,
            post: item.post,
            [item.date]: item.status || 0
          })
        }

      })
      this.postList_info = result;
      console.log("postList_info")
      console.log(this.postList_info)
      return result;
    },
    /** 改变倒班类型 */
    changeShiftType(scope){
      console.log(this.addAttendance_info)
      let rowIndex=scope.$index
      if(scope.row.workShiftType==1){
        this.addEveryDay.forEach((item,index)=>{
          if(item=='周六'||item=='周日'){
            this.addAttendance_info[rowIndex][this.addDateindex[index]]="休"
          }
          else {
            this.addAttendance_info[rowIndex][this.addDateindex[index]]="上"
          }
        })
      }else if(scope.row.workShiftType==2){
        this.addEveryDay.forEach((item,index)=>{
          if(item=='周六'||item=='周日'){
            this.addAttendance_info[rowIndex][this.addDateindex[index]]="上"
          }
          else {
            this.addAttendance_info[rowIndex][this.addDateindex[index]]="休"
          }
        })
      }
      else{
        this.addEveryDay.forEach((item,index)=>{
          this.addAttendance_info[rowIndex][this.addDateindex[index]]=null
        })
      }console.log(this.addAttendance_info)
    },
    /** 新增排班的保存按钮 */
    saveAddAttendance(){
      console.log(this.addAttendance_info)
      let addDetail=[]
      this.addAttendance_info.forEach((tableItem,tableIndex)=>{
        let userId=tableItem.userId
        this.addEveryDay.forEach((item,index)=>{
          let status=null
          if(tableItem[this.addDateindex[index]]=="上"){
            status=0
          }else if(tableItem[this.addDateindex[index]]=="白"){
            status=1
          }else if(tableItem[this.addDateindex[index]]=="夜"){
            status=2
          }else {
            status=3
          }
          if(status!=null){
            addDetail.push({
              userId:userId,
              date:this.addDateindex[index],
              status:status
            })
          }
        })
      })
      console.log("addDetail:")
      console.log(addDetail)
      saveAttendances(addDetail).then(res=>{
        this.msgSuccess("新增成功!");
        this.addParams.month=null
        this.addParams.classID=null
        this.addAttendance_info=[]
        this.addAttendanceVisible=false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        name: null,
        status: null,
        date: null
      };
      this.resetForm("form");
    },
    /** 回显函数 **/
    formatteruserName(row,column){
      return this.selectDept(this.userList,row.userId);
    },
    /** 对应deptId与deptName **/
    selectDept(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].userId == ('' + value)) {
          actions.push(datas[key].nickName);
          return true;
        }
      })
      return actions.join('');
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考勤";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAttendance(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考勤";
      });
    },
    submit(){
      // // 创建新的数据对象   多文件上传
      // let formData = new FormData();
      // //把数组对象存到formData中
      // this.addGoodsForm.goodsSpecsList.forEach((item, i) => {
      //     formData.append(`goodsSpecsList[${i}].userId`, item.spec)
      //     formData.append(`goodsSpecsList[${i}].date`, item.price)
      //     formData.append(`goodsSpecsList[${i}].status`, item.stock)
      // })
      console.log(this.postList_info[0].userId);
      console.log(this.arr);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAttendance(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getAttendanceList();
            });
          } else {
            addAttendance(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getAttendanceList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除考勤编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAttendance(ids);
        }).then(() => {
          this.getAttendanceList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有考勤数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportAttendance(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },

  }
};
</script>
